import {
    ChangeDetectorRef,
    Component,
    ElementRef,
    EventEmitter,
    Input, OnChanges, OnInit,
    Output,
    ViewChild
} from '@angular/core';
import {FileTransfer, FileTransferObject} from '@ionic-native/file-transfer/ngx';
import {File, FileEntry} from '@ionic-native/file/ngx';
import {StorageService} from '../../services/storage.service';
import {NativeService} from '../../services/native.service';
import {DomSanitizer} from '@angular/platform-browser';
import {WebView} from '@ionic-native/ionic-webview/ngx';


@Component({
    selector: 'app-img-storage',
    templateUrl: './img-storage.component.html',
    styleUrls: ['./img-storage.component.scss'],
})
export class ImgStorageComponent implements OnChanges {
    @ViewChild('image', {static: true}) image: ElementRef;
    // tslint:disable-next-line:variable-name
    _imgsrc: any = 'assets/images/replace/bird-loading.gif';
    errorImagSrc = 'assets/images/replace/not_find.jpg';
    fileTransferObject: FileTransferObject;
    @Output()
    load: EventEmitter<any>;
    @Output()
    loadError: EventEmitter<any>;

    lastUpdateTime: any;
    imageStyle = '';
    isStorage: any;

    constructor(private transfer: FileTransfer,
                private file: File,
                private storage: StorageService,
                private sanitizer: DomSanitizer,
                private webview: WebView,
                private native: NativeService,
                private cd: ChangeDetectorRef,) {
        this.fileTransferObject = this.transfer.create();
        this.load = new EventEmitter();
        this.loadError = new EventEmitter();
    }


    ngOnChanges() {
        this.image.nativeElement.style = this.imageStyle;
    }


    @Input()
    set imgsrc(value: string) {
        this._imgsrc = 'assets/images/replace/bird-loading.gif';
        this.storage.read('isStorage').then((data) => {
            if (data == 2 && this.native.isMobile()) {
                if (value && value !== '') {
                    const now = Date.now();
                    this.lastUpdateTime = now;
                    this.download(value, now);
                }
            } else {
                this._imgsrc = value;
            }
        });
    }

    @Input()
    set _imgstyle(value: string) {
        this.imageStyle = value;
    }

    async download(url: string, now: number) {
        let imgSrcTmp: any;
        const imgPath = this.file.dataDirectory;
        const imgDir = 'bird';
        const imgName = url.substr(url.lastIndexOf('/') + 1);
        const android = this.file.dataDirectory;
        const filePath = imgPath + imgDir + '/' + imgName;

        console.log('文件完整路径：' + filePath);
        const isPathExist = await this.file.checkDir(imgPath, imgDir).catch(err => {
            console.log('检查目录出错：', JSON.stringify(err));
            return false;
        });
        console.log('目录是否已存在：' + isPathExist);
        if (!isPathExist) {
            await this.file.createDir(imgPath, imgDir, false).catch(err => {
                console.log('创建目录出错：', JSON.stringify(err));
            });
        }
        const isFileExist = await this.file.checkFile(imgPath, imgDir + '/' + imgName).catch(err => {
            console.log('检查文件出错：', JSON.stringify(err));
        });
        console.log('文件是否已存在：' + isFileExist);
        if (isFileExist) {
            imgSrcTmp = this.sanitizer.bypassSecurityTrustUrl(this.webview.convertFileSrc(filePath));

        } else {
            const entry: FileEntry = await this.fileTransferObject.download(url, filePath);
            if (entry) {
                imgSrcTmp = this.sanitizer.bypassSecurityTrustUrl(this.webview.convertFileSrc(filePath));
                // const file = new Blob([filePath]);
                // const formData = new Compressor(file, {
                //     quality: 0.5,
                //     maxWidth: 800,
                //     maxHeight: 800,
                //     checkOrientation: true,
                //     success(result) {
                //         const reader = new FileReader();
                //         imgSrcTmp = reader.readAsDataURL(result);
                //     },
                //     error(err) {
                //         console.log(err.message);
                //     }
                // });
            } else {
                imgSrcTmp = this.errorImagSrc;
            }
        }

        if (now === this.lastUpdateTime) {
            this._imgsrc = imgSrcTmp;
            this.cd.detectChanges();
        }
    }

    loaded() {
        this.load.emit('loaded');
    }

    loadErrorFunc() {
        this.loadError.emit('loaderror');
    }
}
